package com.quanquan.store.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.quanquan.store.configBean.RabbitSender;
import com.quanquan.store.dto.BuyingDTO;
import com.quanquan.store.dto.GroupBuyingDTO;
import com.quanquan.store.entity.GroupBuying;
import com.quanquan.store.entity.GroupBuyingTradingRecord;
import com.quanquan.store.entity.ShoppingKill;
import com.quanquan.store.repository.GroupBuyingRepository;
import com.quanquan.store.repository.GroupBuyingTradingRecordRepository;
import com.quanquan.store.request.GroupBuyingRequestBody;
import commond.IntegralOutPut;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.JsonUtil;
import utils.StringUtil;
import utils.UUIDGenerator;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Pageable;

import javax.persistence.criteria.Predicate;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class GroupBuyingService {


    private static final String INTEGRAL = "integral";
    private static final String MONEY = "money";

    private final RabbitSender rabbitSender;
    public static final String INVENNTORY = "invenntory";
    private static final String GROUPBUYING = "groupBuying";
    private static final String GROUP_NUM = "groupNum_";
    private static final String STRING = "_";
    private final GroupBuyingTradingRecordService groupBuyingTradingRecordService;
    private final CouponService couponService;
    private final GroupBuyingRepository groupBuyingRepository;
    private final GroupBuyingTradingRecordRepository groupBuyingTradingRecordRepository;

    private final StringRedisTemplate stringRedisTemplate;

    public GroupBuyingService(RabbitSender rabbitSender, CouponService couponService, GroupBuyingRepository groupBuyingRepository, StringRedisTemplate stringRedisTemplate, GroupBuyingTradingRecordService groupBuyingTradingRecordService, GroupBuyingTradingRecordRepository groupBuyingTradingRecordRepository) {
        this.rabbitSender = rabbitSender;
        this.couponService = couponService;
        this.groupBuyingRepository = groupBuyingRepository;
        this.stringRedisTemplate = stringRedisTemplate;
        this.groupBuyingTradingRecordService = groupBuyingTradingRecordService;
        this.groupBuyingTradingRecordRepository = groupBuyingTradingRecordRepository;
    }


    public String createGroupBuying(GroupBuyingRequestBody requestBody) {

        //判断商品的有效时间是否在团购时间范围内 //todo


        GroupBuying groupBuying = new GroupBuying();
        groupBuying.setId(UUIDGenerator.getUUID());
        groupBuying.setCreateTime(DateUtils.currentDate());
        groupBuying.setStartTime(requestBody.getStartTime());
        groupBuying.setEndTime(requestBody.getEndTime());
        groupBuying.setGroupBuyingName(requestBody.getGroupBuyingName());
        //秒杀商品类型
        groupBuying.setGoodsType(requestBody.getGoodsType());
        //库存量
        groupBuying.setInventory(requestBody.getInventory());
        groupBuying.setGroupNum(requestBody.getInventory());
        groupBuying.setThreshold(requestBody.getThreshold());
        String payType = requestBody.getPayType();


        groupBuying.setPayType(payType);

        if (INTEGRAL.equals(payType)) {
            groupBuying.setIntegral(requestBody.getIntegral());
            groupBuying.setOriginalIntegral(requestBody.getOriginalIntegral());
            groupBuying.setOriginalPrice("0");
            groupBuying.setPrice(0.0);
        }
        if (MONEY.equals(payType)) {
            groupBuying.setIntegral(0);
            groupBuying.setOriginalIntegral("0");
            groupBuying.setOriginalPrice(requestBody.getOriginalPrice());
            groupBuying.setPrice(requestBody.getPrice());
        }


        //封面是否要覆盖
        groupBuying.setCoverUrl(requestBody.getCoverUrl());
        groupBuying.setRemove(0);
        groupBuying.setGoodsId(requestBody.getGoodsId());
        groupBuying.setShow(0);

        //判断秒杀状态
        Date startTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getStartTime());
        Date endTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getEndTime());
        Date nowTime = new Date();

        if (nowTime.before(startTime)) {
            //状态准备中
            groupBuying.setKillStatus("preparing");
        } else if (nowTime.after(endTime)) {
            groupBuying.setKillStatus("over");

        } else {
            groupBuying.setKillStatus("processing");

        }
        groupBuying.setContent(requestBody.getContent());
        groupBuying.setUseRule(requestBody.getUseRule());
        Integer inventory = groupBuying.getInventory();

        //优惠券id
        String couponId = groupBuying.getGoodsId();


        //扣除优惠券的抢购库存（秒杀商品变多后要改）todo
        String s = couponService.deductInventory(inventory, couponId);

        if (StringUtil.isNotEmpty(s)) {

            groupBuyingRepository.saveAndFlush(groupBuying);
            //根据库存量和秒杀商品生成缓存id //设置过期时间
            Date endDate = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", requestBody.getEndTime());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            long timeInMillis = calendar.getTimeInMillis();
            long systime = System.currentTimeMillis();//当前系统时间
            long expirTime = (timeInMillis - systime) / 1000;//相差毫秒数
            String inventorys = String.valueOf(groupBuying.getInventory());
            if (expirTime > 0) {
                stringRedisTemplate.opsForValue().set(INVENNTORY + groupBuying.getId(), inventorys, expirTime, TimeUnit.SECONDS);
                String shoppingKillJson = JsonUtil.toJson(groupBuying);
                stringRedisTemplate.opsForValue().set(GROUPBUYING + groupBuying.getId(), shoppingKillJson, expirTime, TimeUnit.SECONDS);
                return "创建成功";

            }
            return "创建失败";

        }
        return null;
        //将秒杀商品缓存到redis
    }


    /**
     * 查询所有的秒杀商品//todo
     *
     * @param
     * @param
     */
    public BuyingDTO queryAllShoppingKill(GroupBuyingRequestBody requestBody) {
        BuyingDTO buyingDTO = new BuyingDTO();
        Integer page = requestBody.getPage() == null ? 0 : requestBody.getPage();
        Integer size = requestBody.getSize() == null ? 100 : requestBody.getSize();
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<GroupBuying> paged = groupBuyingRepository.findAll((Specification<GroupBuying>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            predicates.add(cb.equal(root.get("remove").as(Integer.class), 0));

            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);


        List<GroupBuying> content = paged.getContent();
        for (GroupBuying groupBuying : content) {
            String id = groupBuying.getId();
            String inventory = null;

            //判断秒杀状态
            Date startTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getStartTime());
            Date endTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getEndTime());
            Date nowTime = new Date();

            if (nowTime.before(startTime)) {
                //状态准备中
                groupBuying.setKillStatus("preparing");
                //计算秒数

            } else if (nowTime.after(endTime)) {
                groupBuying.setKillStatus("over");
                //查看是否满足
                groupBuyingTradingRecordService.checkSuccess(id);
            } else {
                groupBuying.setKillStatus("processing");
                //计算秒数
            }
            groupBuyingRepository.saveAndFlush(groupBuying);

            //读取缓存中的库存量jedis
            inventory = stringRedisTemplate.opsForValue().get(INVENNTORY + id);
            System.out.println("库存量是这么多。。。。。。" + inventory);
//                inventory = redisTemplate.opsForValue().get(id).toString();
            if (StringUtil.isEmpty(inventory)) {
                Integer inventoryNum = groupBuyingTradingRecordService.findAllByGroupBuyingId(id);
                if (inventoryNum == 0) {
                    inventory = groupBuying.getInventory().toString();
                } else {
                    inventory = String.valueOf(groupBuying.getInventory() - inventoryNum);
                }
            }
            //根据shoppingKillId 查询记录


            int i = Integer.parseInt(inventory);


            if (i <= 0) {
                groupBuying.setRemainingInventory(0);

            } else {
                groupBuying.setRemainingInventory(i);

            }
            //查询完成支付的用户数
            List<GroupBuyingTradingRecord> groupBuyingTradingRecords = groupBuyingTradingRecordRepository.findByGroupBuyingId2(id);
            int completePayment = groupBuyingTradingRecords.size();
            groupBuying.setCompletePayment(completePayment);
        }
        buyingDTO.setPage(page);
        buyingDTO.setSize(size);
        buyingDTO.setGroupBuyingList(content);
        buyingDTO.setTotal(paged.getTotalElements());
        return buyingDTO;

    }


    /**
     * 查询所有的团购商品前端
     *
     * @param page
     * @param size
     */
    public List<GroupBuying> queryAllGroupBuyingWeb(Integer page, Integer size, String killStatus) {

        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<GroupBuying> paged = groupBuyingRepository.findAll((Specification<GroupBuying>) (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            predicates.add(cb.equal(root.get("remove").as(Integer.class), 0));
            predicates.add(cb.equal(root.get("show").as(Integer.class), 0));
            if(StringUtil.isNotEmpty(killStatus)){
                if(killStatus.equals("over")){
                    Predicate p1 = cb.equal(root.get("killStatus").as(String.class), "sellOut");
                    Predicate p2 = cb.or(cb.equal(root.get("killStatus").as(String.class), "failure"), p1);
                    predicates.add(p2);
                }else{
                    predicates.add(cb.equal(root.get("killStatus").as(String.class), killStatus));

                }

            }

            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);

        List<GroupBuying> groupBuyingList = paged.getContent();

        for (GroupBuying groupBuying : groupBuyingList) {
            String id = groupBuying.getId();
            String inventory = null;
            String groupStatus = groupBuying.getKillStatus();
            Long aLong = null;
            //判断秒杀状态
            Date startTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getStartTime());
            Date endTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getEndTime());
            Date nowTime = new Date();

            if (nowTime.before(startTime)) {
                //状态准备中
                groupBuying.setKillStatus("preparing");
                //计算秒数
                aLong = DateUtils.calculateTime(startTime);

            } else if (nowTime.after(endTime)) {
                groupBuying.setKillStatus("over");
                //查看是否满足
                groupBuyingTradingRecordService.checkSuccess(id);

            } else {
                groupBuying.setKillStatus("processing");
                //计算秒数
                aLong = DateUtils.calculateTime(endTime);
            }
            groupBuying.setCountdown(aLong);
            if (!groupStatus.equals(groupBuying.getKillStatus())) {
                groupBuyingRepository.saveAndFlush(groupBuying);
            }

            //读取缓存中的库存量jedis
            inventory = stringRedisTemplate.opsForValue().get(INVENNTORY + id);
//                inventory = redisTemplate.opsForValue().get(id).toString();
            if (StringUtil.isEmpty(inventory)) {
                Integer inventoryNum = groupBuyingTradingRecordService.findAllByGroupBuyingId(id);
                if (inventoryNum == 0) {
                    inventory = groupBuying.getInventory().toString();
                } else {
                    inventory = String.valueOf(groupBuying.getInventory() - inventoryNum);
                }
            }
            //根据shoppingKillId 查询记录


            int i = Integer.parseInt(inventory);

            if (i <= 0) {
                groupBuying.setInventory(0);
            } else {
                groupBuying.setInventory(i);
            }

            //查询完成支付的用户数
            List<GroupBuyingTradingRecord> groupBuyingTradingRecords = groupBuyingTradingRecordRepository.findByGroupBuyingId2(id);
            int completePayment = groupBuyingTradingRecords.size();
            groupBuying.setCompletePayment(completePayment);
        }

        return groupBuyingList;


    }


    /**
     * 前端查询
     *
     * @param groupBuyingId
     */
    public GroupBuyingDTO queryGroupBuyingDetails(String groupBuyingId) {
        GroupBuyingDTO groupBuyingDTO = new GroupBuyingDTO();
        GroupBuying groupBuying = getGroupBuying(groupBuyingId);
        String inventory = null;

        //读取缓存中的库存量
        inventory = stringRedisTemplate.opsForValue().get(INVENNTORY + groupBuyingId);


        if (StringUtil.isEmpty(inventory)) {
            //根据shoppingKillId 查询记录
            Integer inventoryNum = groupBuyingTradingRecordService.findAllByGroupBuyingId(groupBuyingId);
            if (inventoryNum == 0) {
                inventory = groupBuying.getInventory().toString();
            } else {
                int i = groupBuying.getInventory() - inventoryNum;
                inventory = String.valueOf(i);
            }
            //将秒杀商品缓存上去
            //根据库存量和秒杀商品生成缓存id //设置过期时间
            Date endDate = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getEndTime());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            long timeInMillis = calendar.getTimeInMillis();
            long systime = System.currentTimeMillis();//当前系统时间
            long expirTime = (timeInMillis - systime) / 1000;//相差毫秒数
            if (expirTime > 0) {
                stringRedisTemplate.opsForValue().set(INVENNTORY + groupBuying.getId(), inventory, expirTime, TimeUnit.SECONDS);
            }
//                redisTemplate.opsForValue().set(shoppingKillId, i,expirTime, TimeUnit.SECONDS);

        }


        int i = Integer.parseInt(inventory);
        if (i == 0) {
            groupBuyingDTO.setStatusOver(false);
        } else {
            groupBuyingDTO.setStatusOver(true);
        }
        //通过映射关系来赋值 //TODO 断点看一下
        BeanUtils.copyProperties(groupBuying, groupBuyingDTO);
        groupBuyingDTO.setGroupBuyingId(groupBuyingId);
        if (i <= 0) {
            groupBuyingDTO.setInventory(0);

        } else {
            groupBuyingDTO.setInventory(i);

        }
        groupBuyingDTO.setKillStatus(groupBuying.getKillStatus());
        //查询完成支付的用户数
        List<GroupBuyingTradingRecord> groupBuyingTradingRecords = groupBuyingTradingRecordRepository.findByGroupBuyingId(groupBuyingId);
        int completePayment = groupBuyingTradingRecords.size();

        groupBuyingDTO.setCompletePayment(completePayment);
        long differenceTime=0L;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime startDate = LocalDateTime.parse(groupBuying.getStartTime(), df);
        LocalDateTime endDate = LocalDateTime.parse(groupBuying.getEndTime(), df);
        LocalDateTime now = LocalDateTime.now();
        if(groupBuying.getKillStatus() .equals("preparing")){
            Duration between = Duration.between(startDate, now);
             differenceTime = between.toMillis();
        }
        if(groupBuying.getKillStatus() .equals("processing")){
            Duration between = Duration.between(now, endDate);
            differenceTime = between.toMillis();
        }
        groupBuyingDTO.setCountdown(differenceTime);
        return groupBuyingDTO;
    }

    /**
     * 根据id获取秒杀商品信息
     *
     * @param groupBuyingId
     * @return
     */
    public GroupBuying getGroupBuying(String groupBuyingId) {
        GroupBuying groupBuying = null;
        //根据id查询出
        String groupBuyingJson = stringRedisTemplate.opsForValue().get(GROUPBUYING + groupBuyingId);
        //如果缓存没读到就去读数据库
        if (StringUtil.isNotEmpty(groupBuyingJson)) {
            groupBuying = JsonUtil.fromJava(groupBuyingJson, GroupBuying.class);

        } else {
            groupBuying = groupBuyingRepository.findByIdAndRemove(groupBuyingId, 0);
            //将秒杀商品缓存上去
            //根据库存量和秒杀商品生成缓存id //设置过期时间
            Date endDate = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getEndTime());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            long timeInMillis = calendar.getTimeInMillis();
            long systime = System.currentTimeMillis();//当前系统时间
            long expirTime = (timeInMillis - systime) / 1000;//相差毫秒数
            if (expirTime > 0) {
                String shoppingKillJson1 = JsonUtil.toJson(groupBuying);
                stringRedisTemplate.opsForValue().set(GROUPBUYING + groupBuying.getId(), shoppingKillJson1, expirTime, TimeUnit.SECONDS);
            }


            if (groupBuying == null) {
                return null;
            }
        }
        return groupBuying;
    }

    /**
     * 后端查询
     *
     * @param groupBuyingId
     */
    public GroupBuyingDTO queryGroupBuyingDetailsManagement(String groupBuyingId) {
        GroupBuyingDTO groupBuyingDTO = new GroupBuyingDTO();
        GroupBuying groupBuying = getGroupBuying(groupBuyingId);
        //通过映射关系来赋值 //TODO 断点看一下
        BeanUtils.copyProperties(groupBuying, groupBuyingDTO);
        groupBuyingDTO.setGroupBuyingId(groupBuyingId);

        return groupBuyingDTO;
    }


    /**
     * 更新团购品
     *
     * @param requestBody
     * @return
     */
    public String updateGroupBuying(GroupBuyingRequestBody requestBody) {
        String groupBuyingId = requestBody.getGroupBuyingId();

        GroupBuying groupBuying = groupBuyingRepository.findByIdAndRemove(groupBuyingId, 0);
        String couponId = groupBuying.getGoodsId();

        //只编辑基本信息
        if (requestBody.getInventoryAdjustment() == 0) {

            BeanUtil.copyProperties(requestBody, groupBuying, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

            //判断秒杀状态
            Date startTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getStartTime());
            Date endTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getEndTime());
            Date nowTime = new Date();

            if (nowTime.before(startTime)) {
                //状态准备中
                groupBuying.setKillStatus("preparing");
            } else if (nowTime.after(endTime)) {
                groupBuying.setKillStatus("over");
                //查看是否满足
                groupBuyingTradingRecordService.checkSuccess(groupBuyingId);

            } else {
                groupBuying.setKillStatus("processing");

            }
            groupBuyingRepository.saveAndFlush(groupBuying);
            //根据库存量和秒杀商品生成缓存id //设置过期时间
            Date endDate = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", requestBody.getEndTime());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            long timeInMillis = calendar.getTimeInMillis();
            long systime = System.currentTimeMillis();//当前系统时间
            long expirTime = (timeInMillis - systime) / 1000;//相差毫秒数

            String shoppingKillJson = JsonUtil.toJson(groupBuying);
            if (expirTime > 0) {
                stringRedisTemplate.opsForValue().set(GROUPBUYING + groupBuying.getId(), shoppingKillJson, expirTime, TimeUnit.SECONDS);
            }
            return "修改成功";
        }

        //只编辑基本信息
        if (requestBody.getInventoryAdjustment() == 1) {

            //剩余库存
            String inventory = null;


            //读取缓存中的库存量
            inventory = stringRedisTemplate.opsForValue().get(INVENNTORY + groupBuyingId);

            if (StringUtil.isEmpty(inventory)) {
                //根据shoppingKillId 查询记录
                Integer inventoryNum = groupBuyingTradingRecordService.findAllByGroupBuyingId(groupBuyingId);
                if (inventoryNum == 0) {
                    inventory = groupBuying.getInventory().toString();
                } else {
                    inventory = String.valueOf(groupBuying.getInventory() - inventoryNum);
                }
            }

            int i = Integer.parseInt(inventory);
            //将剩余库存直接还给
            String s = couponService.completionInventory(i, couponId);
            if (StringUtil.isNotEmpty(s)) {
                BeanUtil.copyProperties(requestBody, groupBuying, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                Integer inventory1 = requestBody.getInventory();
                groupBuying.setGroupNum(inventory1);
                //扣除新库存
                //扣除优惠券的抢购库存（秒杀商品变多后要改）todo
                String msg = couponService.deductInventory(inventory1, couponId);
                //更新缓存
                if (StringUtil.isNotEmpty(msg)) {

                    //判断秒杀状态
                    Date startTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getStartTime());
                    Date endTime = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", groupBuying.getEndTime());
                    Date nowTime = new Date();

                    if (nowTime.before(startTime)) {
                        //状态准备中
                        groupBuying.setKillStatus("preparing");
                    } else if (nowTime.after(endTime)) {
                        groupBuying.setKillStatus("over");
                        //查看是否满足
                        groupBuyingTradingRecordService.checkSuccess(groupBuyingId);

                    } else {
                        groupBuying.setKillStatus("processing");

                    }
                    groupBuyingRepository.saveAndFlush(groupBuying);
                    //根据库存量和秒杀商品生成缓存id //设置过期时间
                    Date endDate = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", requestBody.getEndTime());
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(endDate);
                    long timeInMillis = calendar.getTimeInMillis();
                    long systime = System.currentTimeMillis();//当前系统时间
                    long expirTime = (timeInMillis - systime) / 1000;//相差毫秒数
                    if (expirTime > 0) {
                        String inventorys = inventory1.toString();
                        stringRedisTemplate.opsForValue().set(INVENNTORY + groupBuying.getId(), inventorys, expirTime, TimeUnit.SECONDS);

                    }

                    String shoppingKillJson = JsonUtil.toJson(groupBuying);
                    if (expirTime > 0) {
                        stringRedisTemplate.opsForValue().set(GROUPBUYING + groupBuying.getId(), shoppingKillJson, expirTime, TimeUnit.SECONDS);
                    }

                    return "修改成功";
                }
            }
        }
        return null;

    }


    public GroupBuying groupBuyingDetails(String shoppingKillId) {
        GroupBuying shoppingKill = null;
        //根据id查询出
        String shoppingKillJson = stringRedisTemplate.opsForValue().get(GROUPBUYING + shoppingKillId);
        //如果缓存没读到就去读数据库
        if (StringUtil.isNotEmpty(shoppingKillJson)) {
            shoppingKill = JsonUtil.fromJava(shoppingKillJson, GroupBuying.class);

        } else {
            shoppingKill = groupBuyingRepository.findByIdAndRemove(shoppingKillId, 0);


            if (shoppingKill == null) {
                return null;
            }
        }
        Integer show = shoppingKill.getShow();

        if (show == 0) {
            shoppingKill.setShow(1);
        } else {
            shoppingKill.setShow(0);
        }
        groupBuyingRepository.saveAndFlush(shoppingKill);
        //将秒杀商品缓存上去
        //根据库存量和秒杀商品生成缓存id //设置过期时间
        Date endDate = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", shoppingKill.getEndTime());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endDate);
        long timeInMillis = calendar.getTimeInMillis();
        long systime = System.currentTimeMillis();//当前系统时间
        long expirTime = (timeInMillis - systime) / 1000;//相差毫秒数
        if (expirTime > 0) {
            String shoppingKillJson1 = JsonUtil.toJson(shoppingKill);
            stringRedisTemplate.opsForValue().set(GROUPBUYING + shoppingKill.getId(), shoppingKillJson1, expirTime, TimeUnit.SECONDS);
        }


        return shoppingKill;
    }


    //访问自减计数
    public Long decr(String key) {
        Long increment = stringRedisTemplate.opsForValue().increment(INVENNTORY + key, -1);
        System.out.println("increment......." + increment);
        if (increment < 0L) {

            return -1L;
        }
        return increment;
    }


    //访问自增计数
    public Long incr(String key) {
        Long increment = stringRedisTemplate.opsForValue().increment(INVENNTORY + key, 1);

        return increment;
    }


    /**
     * 抢购按钮
     *
     * @param userId
     * @param groupBuying
     * @param openId
     */
    public Map<String, Object> createshoppingRecord(String userId, GroupBuying groupBuying, String openId) {
        //根据秒杀商品id查询商品信息

        //判断商品是否已下架
        Integer show = groupBuying.getShow();
        if (show == 1) {
            return null;
        }
        //创建时间与过期时间做比较判断是否有效
        String startTime = groupBuying.getStartTime();
        String endTime = groupBuying.getEndTime();
        Date stareDate = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", startTime);
        Date endDate = DateUtils.parseStr2Date("yyyy-MM-dd HH:mm", endTime);
        Boolean aBoolean = judgeTime(stareDate, endDate);
        System.out.println("。。。。。。aBoolean。" + aBoolean);
        if (aBoolean) {
            //先确认商品是否还上架//todo 以后会根据需求变动
            Boolean result = couponService.checkCouponStatus(groupBuying.getGoodsId());
            if (result) {
                //发送到队列生成订单
                //判断用户是否能拿到奖励积分和是否推送的券
                //生成订单号作为记录的主键
                String uuid = UUIDGenerator.getUUID();
                //生成订单页面
                boolean record = groupBuyingTradingRecordService.createRecord(userId, groupBuying.getId(), uuid);
                System.out.println("下单是否成功" + record);
                if (!record) {
                    return null;
                }
                System.out.println("wodaozhe l ......");
                HashMap<String, Object> map = new HashMap<>();
                String payType = groupBuying.getPayType();
                System.out.println("payType:" + payType);
                Integer integral = groupBuying.getIntegral();
                String integralPoint = String.valueOf(integral);

                System.out.println(".......我到这了啊"+integralPoint);
                /**
                 * 支付类型  integral 积分  money 现金 combination 组合支付
                 */
                if (INTEGRAL.equals(payType)) {
                    //生成积分记录
                    //用积分支付
                    sountIntegral(integralPoint, groupBuying, userId, uuid);
                    map.put("msg", "商品抢购成功");
                    return map;
                }
                if (MONEY.equals(payType)) {

                    //返回支付页面
                    map.put("uuid", uuid);
                    String shoppingKillId = groupBuying.getId();
                    stringRedisTemplate.opsForValue().set(GROUP_NUM + shoppingKillId + STRING + userId, uuid, 180, TimeUnit.SECONDS);
                    return map;
                }
                //没有设置支付类型
                return null;


            } else {
                //秒杀商品过期了
                return null;
            }


        } else {
            //返回暂未开抢
            return null;
        }


        //生成订单


    }

    private Boolean judgeTime(Date stareDate, Date endDate) {

        Date nowDate = new Date();
        if (nowDate.before(endDate) && nowDate.after(stareDate)) {
            return true;
        } else {
            return false;
        }

    }


    //自助积分
    public boolean sountIntegral(String integralPoint, GroupBuying groupBuying, String userId, String uuid) {
        IntegralOutPut integralOutPut = new IntegralOutPut();
        integralOutPut.setConsumeType("groupBuying");
        integralOutPut.setForeignKeyId(groupBuying.getGoodsId());
        integralOutPut.setIntegralPoint(integralPoint);
        integralOutPut.setMoney("0");
        integralOutPut.setOrderNum(uuid);
        integralOutPut.setUserId(userId);
        integralOutPut.setSource("商品团购");
        integralOutPut.setTradeAction(1);
        integralOutPut.setTradingContent("积分商城商品团购");

        String exchange = "integral.exchange";
        String routingKey = "integral.shoppingKill";
        rabbitSender.sendMessageToMQ(integralOutPut, null, exchange, routingKey);
        return true;
    }

}
